﻿using Dapper.Extensions;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 地锁
    /// </summary>
    public class CarLockController : ApiController
    {
        CarLockService lockService = new CarLockService();
        string FileUploadUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
        private AccessTokenCacheService tokenCacheService = new AccessTokenCacheService();


        /// <summary>
        /// 添加锁
        /// </summary>
        /// <param name="clock"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> AddCarLock(CarLock clock)
        {
            clock.CreateDate = DateTime.Now;
            clock.UpdateDate = DateTime.Now;
            clock.LockStatus = 0;
            clock.IsActive = 1;
            clock.ImageUrl = clock.ImageUrl.Replace(FileUploadUrl, "");
            object id = lockService.Insert(clock);
            return ResultData<int>.Success(Convert.ToInt32(id));
        }

        /// <summary>
        /// 查询当前用户锁
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<CarLock>> GetLocks(int userId, int pageIndex, int pageSize)
        {
            var data = lockService.Pages(userId, pageIndex, pageSize);
            foreach (var item in data.rows)
            {
                if (!string.IsNullOrEmpty(item.ImageUrl))
                {
                    item.ImageUrl = string.Format("{0}/{1}", FileUploadUrl, item.ImageUrl);
                }
            }
            return ResultData<Page<CarLock>>.Success(data);
        }

        /// <summary>
        /// 更新锁
        /// </summary>
        /// <param name="clock"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> UpdateLock(CarLock clock)
        {
            var dbLock = lockService.SingleOrDefault(clock.ID);
            clock.CreateDate = dbLock.CreateDate;
            clock.UserId = dbLock.UserId;
            clock.LockNum = dbLock.LockNum;
            clock.LockStatus = 0;
            clock.UpdateDate = DateTime.Now;
            clock.IsActive = 1;
            clock.ImageUrl = clock.ImageUrl.Replace(FileUploadUrl, "");
            lockService.Update(clock);
            return ResultData<int>.Success(clock.ID);
        }

        /// <summary>
        /// 删除锁
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> DeleteLock(CarLock clock)
        {
            int id = lockService.DeleteLock(clock.ID);
            if (id > 0)
            {
                return ResultData<int>.Success(clock.ID);
            }
            else
            {
                return ResultData<int>.Error("锁id(" + clock.ID + ")不存在");
            }
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<CarLock> GetLock(int id)
        {
            var data = lockService.SingleOrDefault(id);
            if (!string.IsNullOrEmpty(data.ImageUrl))
            {
                data.ImageUrl = string.Format("{0}/{1}", FileUploadUrl, data.ImageUrl);
            }
            return ResultData<CarLock>.Success(data);
        }

        /// <summary>
        /// errNo  
        /// errMessage
        /// accessToken
        /// expiresIn
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public LockToken GetDParkingLockToken()
        {
            AccessTokenCache cache = tokenCacheService.GetActiveToken("carlocktoken");
            if (cache != null)
            {
                return new LockToken()
                {
                    accessToken = cache.AccessToken,
                    errNo = "200"
                };
            }

            //"{\"errNo\":\"200\",\"errMessage\":\"OK\",\"accessToken\":\"288571045ec955d53e67494b6962f2de\",\"expiresIn\":\"3600\"}\n"
            var client = new RestClient("http://test.dingdingtingche.com");
            var request = new RestRequest(string.Format("/ddtcSDK/queryAccessToken?appId={0}&appSecret={1}", "banma", MD5Helper.MD5String("banmachewu").ToLower()), Method.GET);
            IRestResponse response = client.Execute(request);
            var lt = JsonConvert.DeserializeObject<LockToken>(response.Content);
            cache = new AccessTokenCache()
            {
                AccessToken = lt.accessToken,
                ExpireDate = DateTime.Now.AddSeconds(Convert.ToInt32(lt.expiresIn)),
                AppId = "carlocktoken",
                CreateDate = DateTime.Now
            };
            tokenCacheService.Insert(cache);

            return lt;
        }
    }
}
